// 新增机构、编辑机构
import React from 'react';
import { observer, useLocalStore } from 'mobx-react-lite';
import { useLocation, useHistory } from 'react-router';
import { parse } from 'qs';
import { Card, Form, Row, Col, Input, Button, message } from 'antd';
import { genValidConfig } from './pageConfig';
import './index.local.sass';
import { PictureUploader } from '~/components/PictureUploader';
import * as listApi from '~/apis/dashboard/dashboardApi';
import * as userApi from '~/apis/user/addApi';

const FormItem = Form.Item;

const formItemLayout = {
  wrapperCol: { span: 20 },
};

const cardConfig = {
  size: 'small' as const,
  bordered: false,
};


const EditProfileInstitution = observer(() => {
  const location = useLocation();
  const history = useHistory();

  const querryParams = parse(location.search, { ignoreQueryPrefix: true });

  const state = useLocalStore(() => ({
    id: querryParams.id || '',
    loading: false,
  }));

  const [form] = Form.useForm();

  // 获取表单数据
  const getFormValus = () => form.validateFields().then((values: any) => {
    const params = {
      id: state.id,
      ...values,
      headPortrait: values.headPortraitList.map((v: any) => v.response.data).toString(),
    };
    delete params.headPortraitList;
    return params;
  });

  const doSubmit = (type: number) => {
    getFormValus().then((params) => {
      state.loading = true;
      listApi.updateInfo(params).then(() => {
        message.success('success');
        // save and close
        if (type === 2) {
          history.push('/');
        }
      }).finally(() => {
        setTimeout(() => {
          state.loading = false;
        }, 2000);
      });
    }).catch(() => {
      message.error('error');
    });
  };

  const onSubmit = () => {
    doSubmit(1);
  };

  const onSaveAndClose = () => {
    doSubmit(2);
  };

  // 表单填充
  const fillForm = (formData: any) => {
    const { id, nickname, phone, email } = formData;
    form.setFieldsValue({
      id,
      nickname,
      phone,
      email,
    });
  };

  // initForm
  const initForm = (id: string) => {
    userApi.getUser(id).then((res) => {
      fillForm(res.data);
    });
  };

  React.useEffect(() => {
    if (state.id) {
      initForm(state.id);
    }
  }, []);

  return (
    <div className='card-wrap'>
      <Card className='card' {...cardConfig}>
        <Form form={form} layout='vertical' className='w-11/12'>
          <Row>
            <Col span={12}>
              <FormItem
                label="Head portrait"
                name="headPortraitList"
              >
                <PictureUploader
                  max={1}
                  accept="image/jpeg,image/bmp,image/png "
                />
              </FormItem>

              <span className="text-xs cor-grey">Support JPG JPEG PNG BMP only</span>
            </Col>
          </Row>
          {/* line 5 */}
          <Row>
            <Col span={8}>
              <FormItem
                name='nickname'
                label='User Name'
                rules={genValidConfig('UserName')}
                {...formItemLayout}
              >
                <Input className='w-full-fix' placeholder='Please input' />
              </FormItem>
            </Col>
          </Row>

          {/* line 6 */}
          <Row>
            <Col span={8}>
              <FormItem
                name='phone'
                label='Telephone Number'
                rules={[
                  {
                    pattern: /^\S*$/g,
                    message: 'Please input the correct format',
                  },
                ]}
                {...formItemLayout}
              >
                <Input className='w-full-fix' placeholder='Please input' />
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={8}>
              <FormItem
                name='email'
                label='Email'
                rules={[
                  {
                    pattern: /^\S*$/g,
                    message: 'Please input the correct format',
                  },
                  {
                    required: true,
                    message: 'Email is required',
                  },
                ]}
                {...formItemLayout}
              >
                <Input className='w-full-fix' placeholder='Please input' />
              </FormItem>
            </Col>
          </Row>
        </Form>
      </Card>

      <div>
        <Button type='primary' className='mr-2' onClick={onSubmit}>
          Submit Certification
        </Button>

        <Button className='mr-2' onClick={onSaveAndClose}>
          Save and Close
        </Button>
      </div>
    </div>
  );
});

export default EditProfileInstitution;
